package services;

import dao.CommunityDao;
import dao.OrderInfoDao;
import entity.CommunityInfo;
import entity.OrderInfo;
import openConn.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class OrderService {
    public static void changeOrder(int orderId,int comId,int addressId,Double buyCount) throws SQLException {
        Connection connection = DruidUtils.openConn();
        connection.setAutoCommit(false);
        OrderInfo orderInfo = OrderInfoDao.selectById(orderId,connection);
        CommunityInfo communityInfo1 = CommunityDao.selectById(orderInfo.getComId(),connection);
        CommunityDao.update(communityInfo1.getComId(),communityInfo1.getComCount()+orderInfo.getBuyCount(),connection);
        CommunityInfo communityInfo =CommunityDao.selectById(comId,connection);

        CommunityDao.update(comId,communityInfo.getComCount()-buyCount,connection);
        if (communityInfo.getComCount()-buyCount<0){
            System.out.println("库存不足，修改失败");
            connection.rollback();
        }else {
            OrderInfoDao.update(orderId,comId,addressId,buyCount,connection);
            connection.commit();
            System.out.println("修改成功");
        }

    }
    public static void delete(int orderId) throws SQLException {
        Connection connection = DruidUtils.openConn();
        OrderInfo orderInfo = OrderInfoDao.selectById(orderId,connection);
        CommunityInfo communityInfo = CommunityDao.selectById(orderInfo.getComId());
        Double comCount = orderInfo.getBuyCount()+communityInfo.getComCount();
        CommunityDao.update(orderInfo.getComId(),comCount,connection);
        OrderInfoDao.delete(orderId);
    }
}
